import React from 'react';
import { SketchPicker } from 'react-color';
import { Popover } from 'antd';

class ColorPicker extends React.Component {
  static getDerivedStateFromProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      return {
        ...(nextProps.value || {}),
      };
    }
    return null;
  }
  constructor() {
    super();
    this.state = {
      color: '',
      visible: false,
    };

    this.urlInputEl = React.createRef();
  }

  componentDidMount() {}

  inputHandleChange(value) {
    this.triggerChange(value);
  }

  triggerChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(Object.assign({}, { color: changedValue }));
    }
  };
  handleVisibleChange = (visible) => {
    this.setState({
      visible: visible,
    });
  };
  handleChangeComplete = (color) => {
    this.inputHandleChange(color.hex);
  };

  render() {
    return (
      <>
        <Popover
          content={<SketchPicker color={this.state.color} onChangeComplete={this.handleChangeComplete} />}
          title='选颜色'
          trigger='click'
          visible={this.state.visible}
          onVisibleChange={this.handleVisibleChange}
        >
          <div
            style={{
              background: this.state.color,
              width: '40px',
              height: '40px',
              cursor: 'pointer',
              boxShadow: '0 1px 5px rgba(0,0,0,0.2)',
            }}
          />
        </Popover>

        <input ref={this.urlInputEl} name='text' hidden type='text' />
      </>
    );
  }
}

export default ColorPicker;
